import {reqDeleteCarListById, reqShopCartList, reqUpdateCheckedById} from "@/api";

const state={
    cartList:[],
}
const actions={
    //获取购物车商品列表
    async getCartList(context){
        const result=await reqShopCartList();
        if(result.code==200){
            context.commit('GETCARTLIST',result.data)
        }else{
            return Promise.reject(new Error('fail'));
        }
    },
    //删除购物车某一商品
    async deleteCartList(context,skuId){
        let result=await reqDeleteCarListById(skuId);
        if(result.code==200){
            return 'ok'
        }else {
            return  Promise.reject(new Error('fail'));
        }
    },
    //修改购物车某一商品的勾选状态
    async updateCheckedById(context,{skuId,isChecked}){
        let result=await reqUpdateCheckedById(skuId,isChecked);
        console.log(result)
        if(result.code==200){
            return 'ok'
        }else{
            return Promise.reject(new Error('fail'));
        }
    },
    //删除全部勾选的商品
    deleteAllCheckedList({dispatch,getters}){
        let PromiseAll=[]
        getters.cartList.cartInfoList.forEach(item=>{
            let promise=item.isChecked==1?dispatch('deleteCartList',item.skuId):''
            PromiseAll.push(promise)
        })
        //只要全部的p1|p2....都成功，返回结果即为成功
        //如果有一个失败，返回即为失败结果
        return Promise.all(PromiseAll);
    },
    //勾选全选框控制所有商品全选
    updateAllChecked({dispatch,getters},isChecked){
        let PromiseAll=[]
        getters.cartList.cartInfoList.forEach(item=>{
            let promise=dispatch('updateCheckedById',{skuId:item.skuId,isChecked})
            PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll);
    }
}
const mutations={
    GETCARTLIST(state,value){
        state.cartList=value;
    }
}
const getters={
    cartList(){
        return state.cartList[0]|| [];
    },
}
export default {
    state,
    actions,
    mutations,
    getters
}